package leetCode.thread.leetCode1116;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

public class Solution1 implements ZeroEvenOdd{

    private int n;

    Semaphore zero = new Semaphore(1);
    Semaphore even = new Semaphore(0);
    Semaphore odd = new Semaphore(0);


    @Override
    public void zero(IntConsumer printNumber) throws InterruptedException {

        for(int i=0;i<n;i++){
            zero.acquire();
            printNumber.accept(0);
            if(i%2==0){
                odd.release();
            }else even.release();
        }
    }

    @Override
    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i=2;i<=n;i+=2){
            even.acquire();
            printNumber.accept(i);
            zero.release();
        }

    }

    @Override
    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i=1;i<=n;i+=2){
            odd.acquire();
            printNumber.accept(i);
            zero.release();
        }

    }
}
